﻿using CommHelper;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace SDKs
{
    public class AIDoubao
    {
        public class AI
        {
            //如果好用，请收藏地址，帮忙分享。
            public class Message
            {
                /// <summary>
                /// 
                /// </summary>
                public string content { get; set; }
                /// <summary>
                /// 
                /// </summary>
                public string role { get; set; }
            }

            public class ChoicesItem
            {
                /// <summary>
                /// 
                /// </summary>
                public string finish_reason { get; set; }
                /// <summary>
                /// 
                /// </summary>
                public int index { get; set; }
                /// <summary>
                /// 
                /// </summary>
                public string logprobs { get; set; }
                /// <summary>
                /// 
                /// </summary>
                public Message message { get; set; }
            }

            public class Prompt_tokens_details
            {
                /// <summary>
                /// 
                /// </summary>
                public int cached_tokens { get; set; }
            }

            public class Completion_tokens_details
            {
                /// <summary>
                /// 
                /// </summary>
                public int reasoning_tokens { get; set; }
            }

            public class Usage
            {
                /// <summary>
                /// 
                /// </summary>
                public int completion_tokens { get; set; }
                /// <summary>
                /// 
                /// </summary>
                public int prompt_tokens { get; set; }
                /// <summary>
                /// 
                /// </summary>
                public int total_tokens { get; set; }
                /// <summary>
                /// 
                /// </summary>
                public Prompt_tokens_details prompt_tokens_details { get; set; }
                /// <summary>
                /// 
                /// </summary>
                public Completion_tokens_details completion_tokens_details { get; set; }
            }

            public class Root
            {
                /// <summary>
                /// 
                /// </summary>
                public List<ChoicesItem> choices { get; set; }
                /// <summary>
                /// 
                /// </summary>
                public int created { get; set; }
                /// <summary>
                /// 
                /// </summary>
                public string id { get; set; }
                /// <summary>
                /// 
                /// </summary>
                public string model { get; set; }
                /// <summary>
                /// 
                /// </summary>
                public string @object { get; set; }
                /// <summary>
                /// 
                /// </summary>
                public Usage usage { get; set; }
            }
        }

        public class content
        {
            public String model { set; get; }


            private List<message> _messages = new List<message>();

            public List<message> messages
            {
                set { _messages = value; }
                get { return _messages; }
            }

            public Boolean stream { set; get; }


            private thinktype _thinking = new thinktype();

            public thinktype thinking
            {
                set { _thinking = value; }
                get { return _thinking; }
            }
        }

        public class thinktype
        {
            public String type { set; get; }
        }


        public class message
        {
            public String role { set; get; }
            public String content { set; get; }
        }


        public class ChoiceItem
        {
            private message _messages = new message();

            public message messages
            {
                set { _messages = value; }
                get { return _messages; }
            }
        }

        public class Root
        {
            private List<ChoiceItem> _choice = new List<ChoiceItem>();
            public List<ChoiceItem> choice
            {
                set { _choice = value; }
                get { return _choice; }
            }
        }

        public class SentObj
        {
            public String EN { set; get; }
            public String CN { set; get; }

            public String Detail { set; get; }

        }

        public class App
        {
            /// <summary>
            /// 
            /// </summary>
            public string appid { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string token { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string cluster { get; set; }
        }

        public class User
        {
            /// <summary>
            /// 
            /// </summary>
            public string uid { get; set; }
        }

        public class Audio
        {
            /// <summary>
            /// 
            /// </summary>
            public string voice_type { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string encoding { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int compression_rate { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int rate { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int speed_ratio { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int volume_ratio { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public int pitch_ratio { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string emotion { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string language { get; set; }
        }

        public class Request
        {
            /// <summary>
            /// 
            /// </summary>
            public string reqid { get; set; }
            /// <summary>
            /// 字节跳动语音合成
            /// </summary>
            public string text { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string text_type { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string operation { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string silence_duration { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string with_frontend { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string frontend_type { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public string pure_english_opt { get; set; }
        }

        public class AudioRoot
        {
            /// <summary>
            /// 
            /// </summary>
            public App app { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public User user { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public Audio audio { get; set; }
            /// <summary>
            /// 
            /// </summary>
            public Request request { get; set; }
        }

        public class ResponseInfo
        {
            public String data { set; get; }
        }

        public class SenContent
        {
            public String Content { set; get; }
        }

        public class WordInfo
        {
            public String Word { set; get; }
            public Int32 ID { set; get; }
        }



        public class Dr
        {
            public String model { set; get; }
            public String prompt { set; get; }
        }

        public class DrawRequest
        {
            public String model { set; get; }
            public String prompt { set; get; }
            public String Size { set; get; }
            public Boolean watermark { set; get; }
        }

        public class DrawResponse
        {
            public String model { set; get; }

            private List<DrawUrl> _data = new List<DrawUrl>();

            public List<DrawUrl> data
            {
                set { _data = value; }
                get { return _data; }
            }

            private ResponseToken _usage = new ResponseToken();
            public ResponseToken usage
            {
                set { _usage = value; }
                get { return _usage; }
            }
        }

        public class DrawUrl
        {
            public String url { set; get; }
        }

        public class ResponseToken
        {
            public Int32 generated_images { set; get; }
            public Int32 output_tokens { set; get; }
            public Int32 total_tokens { set; get; }
        }

        public static async Task<String> AIDraw(String Msg)
        {
            try
            {
                var client = new HttpClient();
                client.DefaultRequestHeaders.Add("Authorization", "Bearer 3460916e-6b14-48d4-8223-b367f7814efd"); // 确保替换为你的访问令牌

                DrawRequest requestBody = new DrawRequest();
                requestBody.model = "ep-20250812160636-vc8n8";
                requestBody.prompt = Msg;
                requestBody.Size = "600x600";
                requestBody.watermark = false;


                var json = JsonConvert.SerializeObject(requestBody);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                 
                client.Timeout = TimeSpan.FromMinutes(10);
                Console.WriteLine(json);
                var response = await client.PostAsync("https://ark.cn-beijing.volces.com/api/v3/images/generations", content);
                String ImgPath = "";
                if (response.IsSuccessStatusCode)
                {
                    var responseBody = await response.Content.ReadAsStringAsync();
                    Console.WriteLine("结果:" + responseBody); // 打印返回的JSON响应

                    DrawResponse Result = Newtonsoft.Json.JsonConvert.DeserializeObject<DrawResponse>(responseBody);
                    String localFolder = "\\" + DateTime.Now.ToString("yyyy-MM-dd") + "\\AI";

                    String IOFolder = ConfigManager.GetAppSettings("SavePath") + localFolder;




                    if (!System.IO.Directory.Exists(IOFolder))
                    {
                        System.IO.Directory.CreateDirectory(IOFolder);
                    }

                    String FileName = Guid.NewGuid().ToString() + ".jpg";

                    using (WebClient downloader = new WebClient())
                    {
                        downloader.DownloadFile(Result.data[0].url, IOFolder + "\\" + FileName);
                    }

                    ImgPath = "https://nx5.abc5g.com/UploadFiles" + localFolder.Replace("\\", "/") + "/" + FileName;
                }
                else
                {
                    Console.WriteLine($"Error: {response}");
                }
                return ImgPath;
            }
            catch(Exception ex)
            {
                DataManager dm = new DataManager();
                Dictionary<String, String> dic = new Dictionary<string, string>();
                dic.Add("API", "AIDraw");
                dic.Add("Exception", ex.ToString());
                dm.AddError(dic);
                return "";
            }
        }

        private static Random random = new Random();

        public static async Task<string> AIAudio(string inText, string inTextType = "plain")
        {
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer ;j3ODUWEFJoFszfjfIL1KauJoSxgeKbR-"); // 确保替换为你的访问令牌 


            int randomValue = random.Next(2);

            List<string> Voices = new List<string>();
            Voices.Add("BV503_streaming");
            Voices.Add("BV504_streaming");

            string UseVoice = Voices[randomValue];
            Console.WriteLine(UseVoice);
            AudioRoot root = new AudioRoot();
            root.app = new App()
            {
                appid = "5151479556",
                token = "j3ODUWEFJoFszfjfIL1KauJoSxgeKbR-",
                cluster = "volcano_tts"
            };

            root.user = new User()
            {
                uid = "uid123"
            };

            root.audio = new Audio()
            {
                voice_type = UseVoice,
                encoding = "mp3",
                compression_rate = 1,
                rate = 24000,
                speed_ratio = 1,
                volume_ratio = 1,
                pitch_ratio = 1,
                emotion = "happy",
                language = "en"
            };

            root.request = new Request()
            {
                reqid = Guid.NewGuid().ToString(),
                text = inText,
                text_type = inTextType,
                operation = "query",
                silence_duration = "125",
                with_frontend = "1",
                frontend_type = "unitTson",
                pure_english_opt = "1"
            };

            var json = JsonConvert.SerializeObject(root);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            client.Timeout = TimeSpan.FromMinutes(10);
            var response = client.PostAsync("https://openspeech.bytedance.com/api/v1/tts", content).Result;

            string Result = "";
            if (response.IsSuccessStatusCode)
            {
                var responseBody = await response.Content.ReadAsStringAsync();
                //Console.WriteLine("结果:" + responseBody); // 打印返回的JSON响应
                //Console.WriteLine("=======================================================");
                ResponseInfo ri = Newtonsoft.Json.JsonConvert.DeserializeObject<ResponseInfo>(responseBody);
                //Console.WriteLine(ri.data);

                string FileName = Guid.NewGuid().ToString();
                string Path = System.Configuration.ConfigurationManager.AppSettings["SavePath"];
                if (!System.IO.Directory.Exists(Path))
                {
                    System.IO.Directory.CreateDirectory(Path);
                }
                string outputFilePath = Path + "\\audio\\" + FileName + ".mp3"; // 输出文件的路径和名称

                string RelPath = "https://nx5.abc5g.com/UploadFiles/audio/" + FileName + ".mp3";
                try
                {
                    // 将Base64字符串转换为字节数组
                    byte[] data = Convert.FromBase64String(ri.data);

                    // 将字节数组写入文件
                    File.WriteAllBytes(outputFilePath, data);

                    Console.WriteLine("MP3文件已成功保存到: " + outputFilePath);

                    Result = RelPath;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("发生错误: " + ex.Message);
                }

                //messages.Add(mmm);
            }
            else
            {
                Console.WriteLine($"Error: {response.StatusCode}");
            }
            return Result;
        }

        public static async Task<String> AIBase(String msg, Boolean Thinking)
        {
            List<message> messages = new List<message>();

            var client = new HttpClient();
            //client.DefaultRequestHeaders.Add("Content-Type", "application/json; charset=utf-8");
            client.DefaultRequestHeaders.Add("Authorization", "Bearer 3460916e-6b14-48d4-8223-b367f7814efd"); // 确保替换为你的访问令牌

            content requestBody = new content();
            requestBody.model = "ep-20250812160428-dld46";
            requestBody.stream = false;
            if (Thinking)
            {
                requestBody.thinking.type = "enabled";
            }
            else
            {
                requestBody.thinking.type = "disabled";
            }

            //requestBody.thinking.type = "enabled";
            //requestBody.mode = "session";
            //messages.Add(new message()
            //{
            //    role = "system",
            //    content = "你现在是一名英语老师,需要回答学生的问题。"
            //});

            messages.Add(new message()
            {
                role = "user",
                content = msg
            });

            requestBody.messages = messages;
            var json = JsonConvert.SerializeObject(requestBody);
            Console.WriteLine("请求:" + json);
            var content = new StringContent(json, Encoding.UTF8, "application/json");

            String Result = "";
            try
            {


                var response = await client.PostAsync("https://ark.cn-beijing.volces.com/api/v3/chat/completions", content);
                if (response.IsSuccessStatusCode)
                {

                    //byte[] bytes = await response.Content.ReadAsByteArrayAsync();

                    //string test = System.Text.Encoding.UTF8.GetString(bytes);
                    //Console.WriteLine(test);
                    var responseBody = await response.Content.ReadAsStringAsync();


                    //Console.WriteLine("结果:" + responseBody); // 打印返回的JSON响应

                    var x = Newtonsoft.Json.JsonConvert.DeserializeObject<AI.Root>(responseBody);
                    Result = x.choices[0].message.content;
                    //Console.WriteLine(Result);
                    //Console.WriteLine("------------------------------------------------------------------"); 
                }
                else
                {
                    Console.WriteLine($"Error: {response.StatusCode}");
                }
                client.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine($"Exception: {e.Message}");
            }
            return Result;
        }
    }
}
